<template>
  <view class="page">
    <!-- 内容区域 -->
    <view class="main padding-0">
      <!-- 用户信息 -->
      <view class="user-info bg-white padding-sm" @click="toPerson">
        <u-avatar size="36" :src="detail?.creatorAvatar
          ? IMAGE_URL + detail?.creatorAvatar
          : '/static/images/icon-avatar-default.png'
          "></u-avatar>
        <view class="margin-left-sm">
          <view class="nickname">{{ detail?.creatorName }}</view>
          <!-- <view class="time">{{ detail.timeAgo }}</view> -->
        </view>
        <view class="text-left flex-sub">
          <text class="custom-tag">{{ detail?.userIdentity == 2 ? '家长' : '老师' }}</text>
        </view>
      </view>

      <!-- 动态内容 -->
      <view class="bg-white padding-sm">
        {{ detail?.content }}
      </view>
      <!-- 内容图片 -->
      <view v-if="detail?.images" class="padding-lr bg-white">
        <u-album :rowCount="4" :urls="getUrls(detail.images)"></u-album>
      </view>
      <!-- 转发 -->
      <view class="flex bg-white">
        <!-- #ifdef APP-PLUS -->
        <view class="flex-sub text-center" @click="appShare('weixin', 'WXSceneSession')">
          <image src="/static/images/share-wechat.png" style="width: 40px; height: 40px" mode="widthFit"></image>
        </view>
        <view class="flex-sub text-center" @click="appShare('weixin', 'WXSceneTimeline')">
          <image src="/static/images/share-quan.png" style="width: 40px; height: 40px" mode="widthFit"></image>
        </view>
        <view class="flex-sub text-center" @click="appShare('qq', 'WXSceneTimeline')">
          <image src="/static/images/share-qq.png" style="width: 40px; height: 40px" mode="widthFit"></image>
        </view>
        <!-- #endif -->
        <!-- <view class="flex-sub text-center">
          <image
            src="/static/images/save-image.png"
            style="width: 40px; height: 40px"
            mode="widthFit"
          ></image>
        </view> -->
      </view>
      <view class="margin-top bg-white padding">
        <view class="flex">
          <view class="flex-sub">
            <text class="text-muted text-sm">转发 {{ detail?.shareCount }}</text>
            <text class="text-sm margin-left">评论 {{ detail?.commentCount }}</text>
          </view>
          <view class="text-muted text-sm">赞 {{ detail?.likeCount }}</view>
        </view>
        <view class="bg-white">
          <up-divider></up-divider>
        </view>
        <!-- 评论列表 -->
        <view class="comment-list bg-white">
          <view class="comment-item" v-for="(item, index) in commentsList" :key="index">
            <view class="comment-user">
              <u-avatar src="/static/images/icon-avatar-default.png" size="40" shape="circle" />
              <view class="comment-detail">
                <view class="comment-top">
                  <text class="nickname">{{ item.nickname }}</text>
                </view>
                <view class="comment-content">{{ item.comment }}</view>
                <view class="flex justify-center align-center">
                  <view class="flex-sub">
                    <up-text :text="item.createTime" size="10" color="#B7B7B7" margin="20rpx 0 0 0"></up-text>
                  </view>
                  <view>
                    <image src="/static/images/icon-share.png" style="width: 12px; height: 12px"></image>
                    <image src="/static/images/icon-comment.png" style="width: 12px; height: 12px" class="margin-left"
                      @click="todoComment(item.id)"></image>
                    <image :src="item.isLiked
                      ? '/static/images/icon-heart-red.png'
                      : '/static/images/icon-heart.png'
                      " style="width: 12px; height: 12px" class="margin-left" @click="toggleCommentLike(item)"></image>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部互动栏 -->
    <view class="footer bg-white">
      <view class="flex-sub" @click="handleShare">
        <up-text prefixIcon="/static/images/icon-share.png" text="转发" color="##B7B7B7" size="12" align="center"
          :iconStyle="{ marginRight: '4rpx' }"></up-text>
      </view>
      <view class="flex-sub" @click="handleComment">
        <up-text prefixIcon="/static/images/icon-comment.png" text="评论" color="##B7B7B7" size="12" align="center"
          :iconStyle="{ marginRight: '4rpx' }" @click="todoComment(detail.id)"></up-text>
      </view>
      <view class="flex-sub" @click="handleLike">
        <up-text :prefixIcon="detail?.isLiked ? '/static/images/icon-heart-red.png' : '/static/images/icon-heart.png'
          " text="赞" :color="detail?.isLiked ? '#9CB95A' : '#B7B7B7'" size="12" align="center"
          :iconStyle="{ marginRight: '4rpx' }" @click="toggleLike(detail.id)"></up-text>
      </view>
    </view>
    <!-- 发表评论 -->
    <view class="footer flex bg-white" v-if="currentId">
      <view class="flex-sub">
        <up-input placeholder="评论" v-model="commentContent"></up-input>
      </view>
      <view class="margin-left-xs flex">
        <up-button type="primary" size="mini" text="发送" customStyle="width: 50px !important" :disabled="!commentContent"
          @click="postComment"></up-button>
        <up-button size="mini" text="取消" customStyle="width: 50px !important;margin-left:10px"
          @click="closeCommentPanel"></up-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import {
  likeApi,
  getContentApi,
  getCommentApi,
  commentApi,
  cancelLikeApi,
  commentLikeApi,
  commentUnlikeApi
} from '@/api/community';
import { onLoad } from '@dcloudio/uni-app';
import { IMAGE_URL } from '@/utils/env';
// 评论列表数据
const commentsList = ref();
//当前选中的帖子ID，用户回复或转发时使用；
const currentId = ref('');
//评论内容
const commentContent = ref('');
// 动态详情数据
const detail = ref();
onLoad((option) => {
  getContent(option.id);
});

const getUrls = (images) => {
  if (!images) return [];
  return images.split(',').map((item) => IMAGE_URL + item);
};
//贴子详情
const getContent = async (id) => {
  const result = await getContentApi(id);
  if (result.code === 200) {
    detail.value = result.data;
    getCommentList(id);
  }
};

// 评论列表
const getCommentList = async () => {
  const result = await getCommentApi(detail.value.id);
  if (result.code === 200) {
    commentsList.value = result.data;
  }
};

// 切换帖子点赞状态
const toggleLike = () => {
  if (detail.value.isLiked) {
    cancelLike(detail.value.id);
  } else {
    handleLike(detail.value.id);
  }
};
// 点赞
const handleLike = async () => {
  const result = await likeApi(detail.value.id);
  if (result.code === 200) {
    getCommunity();
    uni.$u.toast('点赞成功!');
  }
};
// 取消点赞
const cancelLike = async () => {
  const result = await cancelLikeApi(detail.value.id);
  if (result.code === 200) {
    getCommunity();
    uni.$u.toast('取消成功!');
  }
};
// 切换评论点赞状态
const toggleCommentLike = (item) => {
  if (item.isLiked) {
    commentUnlike(item.id);
  } else {
    commentLike(item.id);
  }
};
// 评论点赞
const commentLike = async (commentId) => {
  const result = await commentLikeApi(commentId);
  if (result.code === 200) {
    getCommentList();
    uni.$u.toast('点赞成功!');
  }
};
// 取消评论点赞
const commentUnlike = async (commentId) => {
  const result = await commentUnlikeApi(commentId);
  if (result.code === 200) {
    getCommentList();
  }
};
// 分享操作
const handleShare = () => {
  uni.navigateTo({
    url: '/pages/community/share?id=' + detail.value.id
  });
};

// 准备评论
const todoComment = (id) => {
  currentId.value = id;
  uni.hideTabBar();
};
// 发送评论
const postComment = async () => {
  const params = {
    id: currentId.value,
    comment: commentContent.value
  };
  const result = await commentApi(params);
  if (result.code === 200) {
    uni.$u.toast('评论成功!');
    uni.showTabBar();
    currentId.value = 0;
    commentContent.value = '';
    getCommunity();
  }
};
// 预览图片
const previewImage = () => {
  uni.previewImage({
    urls: [detail.value.image],
    current: 0
  });
};
// 关闭发表评论
const closeCommentPanel = () => {
  currentId.value = '';
  uni.showTabBar();
};
const toPerson = () => {
  console.log(detail.value)
  uni.navigateTo({
    url: '/pages/community/person?id=' + detail.value.userId
  });
};
// 分享到微信好友
const onShareAppMessage = () => {
  return {
    title: '伴芽',
    // desc: '伴芽',
    path: '/pages/community/content?id=' + detail.value.id,
    imageUrl: detail.value.image
  };
};
// 分享到朋友圈
const onShareTimeline = () => {
  return {
    title: '伴芽',
    query: 'from=moment',
    imageUrl: detail.value.image//'http://files.dalijiao.com/imgs/202311262329262.webp'
  };
};
// 微信分享
const appShare = (provider, scene) => {
  uni.share({
    provider,
    scene, // 分享到聊天界面
    type: 0, // 0图文、1纯文字、2纯图片、3音乐、4视频
    title: '社区好帖',
    summary: detail.value.content,
    href: `/pages/community/content.vue`,
    imageUrl:
      IMAGE_URL +
      '/profile/avatar/2025/05/20/pGwZ9iAazv3h4be8304665d0be10ec3154c8f0057a52_20250520161245A006.png', // 分享缩略图
    success: (res) => {
      console.log('分享成功:', res);
      uni.showToast({
        title: '分享成功',
        icon: 'success'
      });
    },
    fail: (err) => {
      console.log('分享失败:', err);
      uni.showToast({
        title: '分享失败',
        icon: 'none'
      });
    }
  });
};
</script>

<style lang="scss" scoped>
.page {
  background-color: #fefdf8;
}

.user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .nickname {
    font-size: 24rpx;
    color: #20280f;
  }

  .time {
    font-size: 24rpx;
    color: #999;
    margin-top: 4rpx;
  }

  .follow-btn {
    padding: 10rpx 30rpx;
    background-color: #ff5500;
    border-radius: 30rpx;

    .follow-text {
      font-size: 28rpx;
      color: #fff;
    }
  }
}

.comment-list {
  margin-top: 40rpx;

  .comment-item {
    padding: 20rpx 0;
    border-bottom: 2rpx solid #f5f5f5;

    .comment-user {
      display: flex;

      .comment-detail {
        flex: 1;
        margin-left: 20rpx;

        .comment-top {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 10rpx;

          .nickname {
            font-size: 28rpx;
            color: #333;
          }

          .time {
            font-size: 24rpx;
            color: #999;
          }
        }

        .comment-content {
          font-size: 28rpx;
          color: #333;
          line-height: 1.6;
        }
      }
    }

    &:last-child {
      border-bottom: none;
    }
  }
}

.custom-tag {
  background: #ffbbc2;
  color: #f64b5c;
  padding: 2px 5px;
  border-radius: 10px;
  font-size: 12px;
  margin-left: 5px;
  display: inline-block;
}

.share-button {
  background: transparent;
  height: 40px;
}
</style>
